#include "render_dx9.h"
#include "Gut.h"
#include "GutWin32.h"
#include "render_data.h"
LPDIRECT3DDEVICE9 device =NULL;
LPDIRECT3DTEXTURE9 g_pTexture = NULL;
LPD3DXSPRITE lpSprite=NULL;
LPDIRECT3D9 g_pD3D=NULL;

bool InitResourceDX9(void)
{
	g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );   
	D3DCAPS9 d3dCaps;   
	g_pD3D->GetDeviceCaps( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3dCaps );   
	device = GutGetGraphicsDeviceDX9();
	device->SetRenderState(D3DRS_LIGHTING, FALSE);
	device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
	
	printf("hello\n");	
	LoadTexture(L"pic/Background2048.png",&Resource::instance().m_Background);
	LoadTexture(L"pic/dk2048.png",&Resource::instance().m_Character);
	LoadTexture(L"pic/cloud1024.png",&Resource::instance().m_Cloud);
	LoadTexture(L"pic/items1024.png",&Resource::instance().m_Item);
	device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);   
	device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); 
	device->SetSamplerState(0,D3DSAMP_ADDRESSU,D3DTADDRESS_WRAP);
	device->SetSamplerState(0,D3DSAMP_ADDRESSV,D3DTADDRESS_WRAP);
	D3DXCreateSprite(device,&lpSprite);
	return true;

}
__inline void LoadTexture(LPCWSTR _filename,LPDIRECT3DTEXTURE9 *_ppTexture)
{
	D3DXIMAGE_INFO d3dxImageInfo;
	HRESULT hr=D3DXCreateTextureFromFileEx(
		device, 
		_filename,
		D3DX_DEFAULT_NONPOW2, 
		D3DX_DEFAULT_NONPOW2, 
		1, 
		0, 
		D3DFMT_UNKNOWN, 
		D3DPOOL_DEFAULT, 
		D3DX_DEFAULT, 
		D3DX_DEFAULT, 
		0, 
		&d3dxImageInfo, 
		NULL,
		_ppTexture
		);	
	printf("%d,%d\n",d3dxImageInfo.Width,d3dxImageInfo.Height);


}
bool ReleaseResourceDX9(void)
{
	SAFE_RELEASE(g_pTexture);
	SAFE_RELEASE(device);
	SAFE_RELEASE(lpSprite);
	return true;
}
void BeginRenderDX9(void)
{

	device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1.0f, 0);
	device->BeginScene(); 
	
}
void EndRenderDX9(void)
{
	device->EndScene(); 
	device->Present( NULL, NULL, NULL, NULL );
}
void RenderFrameDX9(Sprite* _sprite,LPDIRECT3DTEXTURE9 _lpTexture)
{
	Vertex_VT vt=_sprite->GetPosition();
	 
	RECT rt;
	SetRect(&rt,vt.m_Texcoord[0],vt.m_Texcoord[1],vt.m_Texcoord[0]+_sprite->stride_x,vt.m_Texcoord[1]+_sprite->stride_y);
	lpSprite->Begin( D3DXSPRITE_ALPHABLEND );   
	//printf("Render:%d'%d\n",vt.m_Position[0],vt.m_Position[1]);
	lpSprite->Draw( _lpTexture,   
		&rt,   
		new D3DXVECTOR3(0,0,0),  
		new D3DXVECTOR3(vt.m_Position[0],vt.m_Position[1],0),  
		D3DCOLOR_COLORVALUE(1.0f,1.0f,1.0f,1.0f) );   
	lpSprite->End();

	
}